package com.hutao.manage.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.hutao.manage.datasource.TargetDataSource;
import com.hutao.manage.mapper.BasicInfoMapper;
import com.hutao.manage.mapper.CitizensInfoMapper;
import com.hutao.manage.mapper.FirstLevelMedicalMapper;
import com.hutao.manage.mapper.HospitalizationNoteMapper;
import com.hutao.manage.mapper.MedicalResourceExaminationMapper;
import com.hutao.manage.model.HospitalVisitBasicInfo;
import com.hutao.manage.pojo.CitizensInfo;
import com.hutao.manage.pojo.FirstLevelMedical;
import com.hutao.manage.pojo.HospitalizationNote;
import com.hutao.manage.pojo.MedicalResourceExamination;
import com.hutao.manage.pojo.TreatmentTrace;
import com.hutao.manage.service.MedicalRecordService;
import com.hutao.manage.service.TreatmentTraceService;
import com.hutao.manage.util.CustomerLogUtil;
import com.hutao.manage.util.ExceptionUtil;
import com.hutao.manage.util.FileUtil;
import com.hutao.manage.util.Result;
import com.hutao.manage.util.StringUtil;
@Service
public class MedicalRecordServiceImpl implements MedicalRecordService {
	private Logger log = LoggerFactory.getLogger(MedicalRecordServiceImpl.class);

	@Autowired
	private CitizensInfoMapper citizensInfoMapper;
	
	@Autowired
	private MedicalResourceExaminationMapper medicalResourceExaminationMapper;
	
	@Autowired
	private FirstLevelMedicalMapper firstLevelMedicalMapper;
	
	@Autowired
	private HospitalizationNoteMapper hospitalizationNoteMapper;
	
	@Autowired
	private BasicInfoMapper baseInfoMapper;
	
	@Autowired
	private TreatmentTraceService treatmentTraceService;
	
	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int updateHospitalizationNoteBasic(HospitalVisitBasicInfo hospitalVisit) {
		// TODO Auto-generated method stub
		FirstLevelMedical firstLevelMedical = firstLevelMedicalMapper.selectByPrimaryKey(hospitalVisit.getVisitGuid());
		CitizensInfo citizensInfo = citizensInfoMapper.selectByPrimaryKey(firstLevelMedical.getCitizensGuid());
		citizensInfo.setName(hospitalVisit.getPatientName());
		List<Map<String,Object>> sexs = baseInfoMapper.getSexIdsByName(hospitalVisit.getSexName());
		if(!sexs.isEmpty()){
			citizensInfo.setSexId((Integer)sexs.get(0).get("id"));
		}
		
		citizensInfo.setBirthday(hospitalVisit.getBirthday());
		citizensInfo.setIdNumber(hospitalVisit.getIdNumber());
		citizensInfoMapper.updateByPrimaryKey(citizensInfo);
		HospitalizationNote hospitalizationNote = hospitalizationNoteMapper.selectByFirstGuid(hospitalVisit.getVisitGuid());
		hospitalizationNote.setMrId(hospitalVisit.getMrId());
		hospitalizationNote.setOnlyId(hospitalVisit.getOnlyId());
		hospitalizationNote.setVisitNumber(hospitalVisit.getVisitNumber()==null?null:hospitalVisit.getVisitNumber().intValue());
		
		List<Map<String,Object>> inMedicalOffices = baseInfoMapper.getMedicalOfficeByName(hospitalVisit.getInDeptName());
		if(!inMedicalOffices.isEmpty()){
			hospitalizationNote.setInDeptId((Integer)inMedicalOffices.get(0).get("id"));
		}
		
		hospitalizationNote.setInHospitalDate(hospitalVisit.getInHospitalDateTime());
		List<Map<String,Object>> outMedicalOffices = baseInfoMapper.getMedicalOfficeByName(hospitalVisit.getOutDeptName());
		if(!outMedicalOffices.isEmpty()){
			hospitalizationNote.setOutDeptId((Integer)outMedicalOffices.get(0).get("id"));
		}
		hospitalizationNote.setOutHospitalDate(hospitalVisit.getOutHospitalDateTime());
		
		List<Map<String,Object>> inHospitalTypes = baseInfoMapper.getInHospitalTypeByName(hospitalVisit.getInHospitalTypeName());
		if(!inHospitalTypes.isEmpty()){
			hospitalizationNote.setInHospitalTypeId((Integer)inHospitalTypes.get(0).get("id"));
		}
		
		List<Map<String,Object>> outHospitalTypes = baseInfoMapper.getOutHospitalTypeByName(hospitalVisit.getOutHospitalTypeName());
		if(!outHospitalTypes.isEmpty()){
			hospitalizationNote.setOutHospitalTypeId((Integer)outHospitalTypes.get(0).get("id"));
		}
		hospitalizationNoteMapper.updateByPrimaryKey(hospitalizationNote);
		return firstLevelMedicalMapper.updateByPrimaryKey(firstLevelMedical);
	}

	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int updateHospitalizationSpecialIndication(String guid, Integer specialIndication) {
		HospitalizationNote hospitalizationNote = hospitalizationNoteMapper.selectByFirstGuid(guid);
		hospitalizationNote.setSpecialIndication(specialIndication);
		hospitalizationNoteMapper.updateByPrimaryKeySelective(hospitalizationNote);
		return 0;
	}

	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public Result addMedicalResourceExamination(List<String> pdfImageList, String userName, String firstGuid) {
		try {
			if (CollectionUtils.isNotEmpty(pdfImageList)) {
				MedicalResourceExamination medicalResourceExamination = null;
				String groupId = StringUtil.getTimeId();
				
				for (String pdfImageName : pdfImageList) {
					medicalResourceExamination = new MedicalResourceExamination();
					medicalResourceExamination.setCreateTime(new Date());
					medicalResourceExamination.setFileName(pdfImageName);
					medicalResourceExamination.setFirstGuid(firstGuid);
					medicalResourceExamination.setStatus(1);
					medicalResourceExamination.setGroupId(groupId);
					medicalResourceExaminationMapper.insertSelective(medicalResourceExamination);
				}
			}
			
			TreatmentTrace treatmentTrace = new TreatmentTrace();
			String currentUser = userName;
			treatmentTrace.setUserId(currentUser);
			treatmentTrace.setTraceDate(new Date());
			treatmentTrace.setTraceTypeId(7);
			treatmentTrace.setTreatmentGuid(firstGuid);
			treatmentTraceService.addMedTraceQuery(treatmentTrace);
			return new Result(true, "病案发行成功");
		} catch (Exception e) {
			log.error("病案上架异常  firstGuid = " + firstGuid + " " + ExceptionUtil.getStackTrace(e));
			return new Result(true, "病案发行失败");
		}
	}
	
	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int addMedicalResourceExaminationForScan(List<String> pdfImageList, String userName, String firstGuid,String imgDir) {
		try {
			if (CollectionUtils.isNotEmpty(pdfImageList)) {
				MedicalResourceExamination medicalResourceExamination = null;
				String groupId = StringUtil.getTimeId();
				for (String pdfImageName : pdfImageList) {
					medicalResourceExamination = new MedicalResourceExamination();
					medicalResourceExamination.setCreateTime(new Date());
					medicalResourceExamination.setFileName(pdfImageName);
					medicalResourceExamination.setFirstGuid(firstGuid);
					medicalResourceExamination.setStatus(1);
					medicalResourceExamination.setGroupId(groupId);
					medicalResourceExaminationMapper.insertSelective(medicalResourceExamination);
				}
			}
			
			String groupId = "";
			//删除并发产生的数据
			List<Map<String, Object>> mreList = this.getMreGroupIdByFirstGuid(firstGuid);
			if (null != mreList && mreList.size() > 1) {
				for(int i = 0; i < mreList.size()-1; i++) {
					Map<String, Object> mre = mreList.get(i);
					groupId = (String)mre.get("group_id");
					List<Map<String, Object>> list = medicalResourceExaminationMapper.getMreListByfirstGuidAndGroupId(groupId, firstGuid);
					if (null != list && list.size() > 0) {
						for (int j = 0; j < list.size(); j++) {
							Map<String, Object> mre1 = list.get(j);
							String fileName = (String)mre1.get("file_name");
							FileUtil.deleteFile(imgDir + fileName);
						}
					}
					
					medicalResourceExaminationMapper.deleteByGroupId(groupId, firstGuid);
					
				}
			}
			return 1;
		} catch (Exception e) {
			log.error("依据模板生成检验报告单异常  firstGuid = " + firstGuid + " " + ExceptionUtil.getStackTrace(e));
			return -1;
		}
	}
	
	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int deleteUploadVisitGuid(String firstGuid) {
		return firstLevelMedicalMapper.deleteUploadVisitGuid(firstGuid);
	}
	
	
	@TargetDataSource(name="ds1")
	@Transactional(readOnly = true)
	@Override
	public List<MedicalResourceExamination> getMedicalExaminationPicByGuid(String firstGuid) {
		List<MedicalResourceExamination> mreList = medicalResourceExaminationMapper.getMedicalExaminationPicByGuid(firstGuid);
		return mreList;
	}
	
	@TargetDataSource(name="ds1")
	@Transactional(readOnly = true)
	@Override
	public List<Map<String, Object>> getMreGroupIdByFirstGuid(String firstGuid) {
		List<Map<String, Object>> mreList = medicalResourceExaminationMapper.getMreGroupIdByFirstGuid(firstGuid);
		return mreList;
	}
	
	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public void deleteMreByGroupId(String firstGuid, String imgDir) {
		String groupId = "";
		
		try {
			//删除并发产生的数据
			List<Map<String, Object>> mreList = this.getMreGroupIdByFirstGuid(firstGuid);
			
			if (null != mreList && mreList.size() > 1) {
				for(int i = 0; i < mreList.size()-1; i++) {
					Map<String, Object> mre = mreList.get(i);
					groupId = (String)mre.get("group_id");
					List<Map<String, Object>> list = medicalResourceExaminationMapper.getMreListByfirstGuidAndGroupId(groupId, firstGuid);
					if (null != list && list.size() > 0) {
						for (int j = 0; j < list.size(); j++) {
							Map<String, Object> mre1 = list.get(j);
							String fileName = (String)mre1.get("file_name");
							FileUtil.deleteFile(imgDir + fileName);
						}
					}
					
					medicalResourceExaminationMapper.deleteByGroupId(groupId, firstGuid);
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("---删除MedicalResourceExamination失败  --groupId=" + groupId + " firstGuid=" + firstGuid );
			CustomerLogUtil.writeLogDeleteMre("删除数据库 medical_resource_examiantion 异常  firstGuid = " + firstGuid + "  groupId="+groupId 
					+ "  异常信息:" + ExceptionUtil.getStackTrace(e));
		}
		
	}
	
	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public Map<String, Object> getHospitalizationNoteByFirstGuid(String firstGuid) {
		List<Map<String, Object>>  list = hospitalizationNoteMapper.getHospitalizationNoteByFirstGuid(firstGuid);
		
		if (null != list && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	
	
	
	
	

}




